package com.ydl.iec.demo;

import com.ydl.iec.iec104.server.handler.ChannelHandler;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

@Slf4j
@Data
public class ViewPanel {
    JFrame frame;
    Map<Integer, Component> components = new HashMap<>();//key 点号
    ViewPanel(ResourceManage resourceManage) {
        frame = new JFrame("显示变量值");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置默认关闭操作
        frame.setSize(1000, 400); // 设置窗口大小
        frame.setLayout(new GridLayout(1, 3));
//        frame.setLayout(new java.awt.FlowLayout()); // 使用FlowLayout布局管理器
        resourceManage.getResources().keySet().forEach(key -> {
            Resource resource = resourceManage.getResources().get(key);
            JLabel resourceName = new JLabel(resource.getResourceName());
            JPanel panel = new JPanel(new GridLayout(12, 2));
            panel.setName(resource.getResourceName());
            panel.add(resourceName);
            panel.add(new JLabel());
            resource.getPoints().keySet().forEach(pointId -> {

                Point point = resource.getPoints().get(pointId);
                panel.add(new JLabel(point.getPointName() + ":"));
                SelectAllTextField jTextField = new SelectAllTextField();
                jTextField.setText(String.valueOf(point.getValue()));
                jTextField.setOldText(String.valueOf(point.getValue()));
                jTextField.setPointId(point.getPointId());
                jTextField.setResourceId(resource.getResourceId());
                jTextField.setName(point.getPointName());
                panel.add(jTextField);
                components.put(pointId,jTextField);
            });
            JButton above = new JButton("模拟超限");
            above.addActionListener(e -> {
                resource.setRatio(10f);
            });
            panel.add(above);
            JButton normal = new JButton("恢复正常");
            normal.addActionListener(e -> {
                resource.setRatio(1);
            });
            panel.add(normal);

            // 将JLabel添加到JFrame中
            frame.getContentPane().add(panel);
        });
        // 设置窗口居中显示
        frame.setLocationRelativeTo(null);

        // 使窗口可见
        frame.setVisible(true);

    }

    public void updateView(Point point) {
        Component component = components.get(point.getPointId());
        if(component instanceof JTextField){
            ((JTextField)component).setText(String.valueOf(point.getValue()));
        }
    }


    @Data
    public class SelectAllTextField extends JTextField {
        public String resourceId;
        public Integer pointId;
        public String oldText;


        public SelectAllTextField() {
            //监听鼠标点击事件
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 1) { // 单击事件
                        selectAll(); // 选中所有内容
                        oldText = getText();
                    }
                }
            });
            //监听焦点
            addFocusListener(new FocusListener() {
                @Override
                public void focusGained(FocusEvent e) {
//                    System.out.println("Gained focus");
                    setOldText(getText());
                }

                @Override
                public void focusLost(FocusEvent e) {
//                    System.out.println("Lost focus");
                    // 在这里处理失去焦点时的逻辑，比如获取文本
                    updatePointValue();
                }
            });

            //监听文本框内容变化
            getDocument().addDocumentListener(new DocumentListener() {

                @Override
                public void insertUpdate(DocumentEvent e) {
//                    System.out.println("insertUpdate"+getPointId());
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
//                    System.out.println("removeUpdate"+getPointId());
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
//                    System.out.println("changedUpdate"+getPointId());
                }
            });


            //监听回车键
            AbstractAction enterAction = new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    updatePointValue();
                }
            };

            this.getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enterAction");
            this.getActionMap().put("enterAction",enterAction);
        }
        //更新测点值
        private void updatePointValue() {
            Point point = Test.resourceManage.getPoint(resourceId, pointId);
            String trim = getText().trim();
            try {
                float v = Float.parseFloat(trim);
                float oldValue = point.getValue();
                point.setValue(v);
                if(point.getPointType()==Const.YX && v!=oldValue){
                    //遥信点并且数值变化
                    ChannelHandler ctx = Test.slaveTest.getSysDataHandler().getCtx();
                    if(ctx!=null)
                        Test.slaveTest.getSysDataHandler().sendYx(point);
                }
                log.info("{}输入数字={}",point.getPointId(),v);
            } catch (Exception exception) {
                log.info(oldText);
                setText(oldText);
//                revalidate(); // 重新验证布局
//                repaint(); // 强制重绘组件
                JOptionPane.showMessageDialog(null, "请输入数字");
            }
        }
    }
}
